package com.pmmaster.admin.interceptor;

import com.pmmaster.common.api.Result;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ValidationException;

@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 运行时异常捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result runtimeExceptionEntity(Exception e) {
        return Result.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result handleException(MissingServletRequestParameterException e) {
        return Result.validateFailed("参数：" + e.getParameterName() + "缺失");
    }

    @ResponseBody
    @ExceptionHandler(MissingPathVariableException.class)
    public Result missParamException(MissingPathVariableException e) {
        return Result.validateFailed("参数：" + e.getVariableName() + "缺失");
    }

    @ResponseBody
    @ExceptionHandler(ValidationException.class)
    public Result validateException(ValidationException e) {
        return Result.validateFailed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result messageException(HttpMessageNotReadableException e) {
        return Result.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(BindException.class)
    public Result binException(BindException e) {
        return Result.validateFailed(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = {Exception.class})
    public Result error(Exception e) {
        return Result.failed(e.getMessage());
    }
}
